package stewardapplet

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"log"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/automate"
	"yundian/internel/app/models/goods"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/room"
	"yundian/internel/app/models/ticket"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/wechatpay"
	"yundian/internel/pkg/wxpay"
)

// HandleRefundResult 退款通知V3 -- 退款已更改为V3
//&{map[
//create_time:2023-01-28T17:21:21+08:00
//event_type:REFUND.SUCCESS
//id:835ade44-27d5-594c-a4a8-98c8d59590b5
//resource:map[
//	algorithm:AEAD_AES_256_GCM
//	associated_data:refund
//	ciphertext:yDxim0qVfQxfmH5aHEJ5PQIN6i+0cwZblJBOFzmftAtw73f9oQe5RDJ0dOU6wsqRAstDmV+pZP07iV3DazTs3czzq/
//	g0k3ErelNw6VV0r5m0IUILI20pW0WUun35zf3b/up1LbXV5rKkMmeX5YUUUlRP4n7GwUr/qLPrilNE+q/vlWt7NdI7rAb71NYXSvkf
//	ZPtiNjry31AZTBDLhtIQ5BCW9iDbsjtou47ZB1Y4pBD7BMKAASF8AlUklpNDXcJMo4PxBnfWwGAERH55qM80IKNXqmpehtQBZKqt0O
//	NFDaFy5LelVNtp2RPrH8K7KjrIT5MFeHDzYnlTH3CEjjVuePKCksZvsfky++9ayGj62WIihx4FIPzS2RbA/+UedU+V981QoXrgOuBO
//	BgFqp3ndiQ/QPRM6onprIQh8g92kklcJh7XLhJh1+MSNJycXxTPmyGOXHd+rcz7B+bkLMvlT2NSBXbH5m317NsSr4d0DnZfdATx7zo
//	mAfMx0e2Ai6NrXdARyVGkzDjPeetO7rGkL
//	nonce:8WmXJOZij0Ix
//	original_type:refund
//]
//resource_type:encrypt-resource
//summary:退款成功]}
func HandleRefundResult(ctx *gin.Context) {
	// todo 获取请求body
	reqData := wechatpay.NewPayData()
	err := reqData.FromJson(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wechatpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,退款结果通知", reqData)

	// todo 获取支付配置信息
	var wc *paysetting.PaySetting
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	} else {
		wc = logic.NewSettingLogic().GetPaySetting()
	}

	// todo 解密退款数据
	dt, err := reqData.DecryptBody(wc)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	resultData := wechatpay.NewPayData()
	err = resultData.FromJsonStr(dt)
	log.Println("打印测试数据,解密后的退款结果信息", resultData)
	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("refund_id") || resultData.Get("refund_id") == "" {
		zap.L().Error("refund_id 微信退款单号不存在")
		return
	}

	// todo 退款记录校验
	c := dao.NewRefundDao().CountRefundByOutRefundNo(resultData.Get("refund_id")).Unwrap().(int64)
	if c == 0 {
		_ = logic.NewOrderLogic().HandleRefundLogic(resultData)
	}

	// todo 返回success
	ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
	return
}

// 订单提现退款专用
func HandleRefResult(ctx *gin.Context) {
	// todo 获取请求body
	reqData := wechatpay.NewPayData()
	err := reqData.FromJson(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wechatpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,退款结果通知", reqData)

	// todo 获取支付配置信息
	var wc *paysetting.PaySetting
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	} else {
		wc = logic.NewSettingLogic().GetPaySetting()
	}

	// todo 解密退款数据
	dt, err := reqData.DecryptBody(wc)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	resultData := wechatpay.NewPayData()
	err = resultData.FromJsonStr(dt)
	log.Println("打印测试数据,解密后的退款结果信息", resultData)
	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("refund_id") || resultData.Get("refund_id") == "" {
		zap.L().Error("refund_id 微信退款单号不存在")
		return
	}

	// todo 退款记录校验
	c := dao.NewRefundDao().CountRefundByOutRefundNo(resultData.Get("refund_id")).Unwrap().(int64)
	if c == 0 {
		_ = logic.NewOrderLogic().HandleRefLogic(resultData)
	}

	// todo 返回success
	ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
	return
}

func CommonPayGoodsResult(ctx *gin.Context) (bool, *wxpay.PayData) {
	resultData := wxpay.NewPayData()
	err := resultData.FromXml(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return false, resultData
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,支付结果通知", resultData)

	wc := logic.NewSettingLogic().GetPaySettingByAppid(resultData.Get("appid"))

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("transaction_id") || resultData.Get("transaction_id") == "" {
		zap.L().Error("transaction_id 微信订单号不存在")
		return false, resultData
	}

	// 验证微信订单
	apiData := wxpay.NewPayData()
	apiData.Set("transaction_id", resultData.Get("transaction_id"))

	respData, err := wxpay.ApiOrderQuery(payClient, apiData, wc)
	if err != nil {
		zap.L().Error("error order query - 微信订单查询失败")
		return false, resultData
	}

	// 验证成功
	if respData.Get("return_code") == wxpay.RCSuccess && respData.Get("result_code") == wxpay.RCSuccess {
		return true, resultData
	}
	return false, resultData
}

func HandlePayGoodsResult(ctx *gin.Context) {
	resultData := wxpay.NewPayData()
	err := resultData.FromXml(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,支付结果通知", resultData)

	wc := logic.NewSettingLogic().GetPaySettingByAppid(resultData.Get("appid"))

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("transaction_id") || resultData.Get("transaction_id") == "" {
		zap.L().Error("transaction_id 微信订单号不存在")
		return
	}

	// 验证微信订单
	apiData := wxpay.NewPayData()
	apiData.Set("transaction_id", resultData.Get("transaction_id"))

	respData, err := wxpay.ApiOrderQuery(payClient, apiData, wc)
	if err != nil {
		zap.L().Error("error order query - 微信订单查询失败")
		return
	}

	// 验证成功
	if respData.Get("return_code") == wxpay.RCSuccess && respData.Get("result_code") == wxpay.RCSuccess {
		tradeNo := resultData.Get("out_trade_no")
		thirdTradeNo := resultData.Get("transaction_id")

		orderList := dao.NewGoodsDao().GetGoodsOrdersListByTradeNo(tradeNo, 0).Unwrap().([]*goods.OrderUpdate)
		if len(orderList) == 0 {
			return
		}
		param := &placemodel.PlacesServiceNotification{
			MemberId:         orderList[0].MemberId,
			PlaceId:          orderList[0].PlaceId,
			UserId:           orderList[0].UserId,
			PlaceName:        orderList[0].PlaceName,
			PlaceRoom:        orderList[0].Address,
			DeviceSn:         orderList[0].DeviceSn,
			NotificationType: helper.TypeNumNotificationTypeGoods,
			Status:           helper.TypeNumNotificationStatusWait,
			Info:             "超市服务",
			Message:          orderList[0].Message,
			MemberPhone:      memberdao.NewMemberDao().GetMemberInfoById(orderList[0].MemberId).Unwrap().(*membermodel.MembersModel).Phone,
		}
		if notificationsInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(param); notificationsInfo.Id <= 0 {
			return
		} else {
			params := &goods.OrderUpdate{
				TradeNo:        tradeNo,
				ThirdTradeNo:   thirdTradeNo,
				NotificationId: notificationsInfo.Id,
				Status:         helper.TypeNumGoodsOrderStatusDonePay,
			}
			if err = dao.NewGoodsDao().UpdateGoodsOrders(params); err != nil {
				zap.L().Error(err.Error())
				return
			}
		}

		ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
	}
}

func HandlePayAutomateResult(ctx *gin.Context) {
	ok, resultData := CommonPayGoodsResult(ctx)
	if !ok || resultData.Get("return_code") != wxpay.RCSuccess || resultData.Get("result_code") != wxpay.RCSuccess {
		return
	}

	tradeNo := resultData.Get("out_trade_no")
	thirdTradeNo := resultData.Get("transaction_id")
	param := &automate.OrderPayDb{
		OrderDb: automate.OrderDb{
			TradeNo:      tradeNo,
			ThirdTradeNo: thirdTradeNo,
			Status:       helper.TypeNumOrderAutomateStatusWaitSend,
		},
		PayTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	orderData := dao.NewAutomateDaoDao().GetGoodsOrderInfoByTradeNo(tradeNo)
	orderInfo := orderData.Unwrap().(*request.GetGoodsOrderInfoByIdRes)
	if orderInfo.Status == helper.TypeNumOrderAutomateStatusWaitDone {
		param.Status = 0
	}

	if dao.NewAutomateDaoDao().UpdateGoodsOrder(param).Err != nil {
		return
	}

	ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
}

func HandlePayTicketResult(ctx *gin.Context) {
	ok, resultData := CommonPayGoodsResult(ctx)
	if !ok || resultData.Get("return_code") != wxpay.RCSuccess || resultData.Get("result_code") != wxpay.RCSuccess {
		return
	}

	tradeNo := resultData.Get("out_trade_no")
	thirdTradeNo := resultData.Get("transaction_id")
	param := &ticket.OrderModel{PayTime: time.Now().Format("2006-01-02 15:04:05")}
	param.ThirdTradeNo = thirdTradeNo
	param.TradeNo = tradeNo

	if data := dao.NewTicketDaoDao().UpdateTicketOrders(param); data.Err != nil {
		return
	}
	ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
}

func HandlePayRoomResult(ctx *gin.Context) {
	resultData := wxpay.NewPayData()
	err := resultData.FromXml(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,支付结果通知", resultData)

	wc := logic.NewSettingLogic().GetPaySettingByAppid(resultData.Get("appid"))

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("transaction_id") || resultData.Get("transaction_id") == "" {
		zap.L().Error("transaction_id 微信订单号不存在")
		return
	}

	// 验证微信订单
	apiData := wxpay.NewPayData()
	apiData.Set("transaction_id", resultData.Get("transaction_id"))

	respData, err := wxpay.ApiOrderQuery(payClient, apiData, wc)
	if err != nil {
		zap.L().Error("error order query - 微信订单查询失败")
		return
	}

	// 验证成功
	if respData.Get("return_code") == wxpay.RCSuccess && respData.Get("result_code") == wxpay.RCSuccess {
		tradeNo := resultData.Get("out_trade_no")
		thirdTradeNo := resultData.Get("transaction_id")
		amount, _ := strconv.Atoi(resultData.Get("cash_fee"))

		dataInfo := dao.NewRoomDaoDao().GetRoomOrderPlace(tradeNo)
		param := &placemodel.PlacesServiceNotification{
			MemberId:         dataInfo.MemberId,
			PlaceId:          dataInfo.PlaceId,
			PlaceName:        dataInfo.PlaceName,
			PlaceRoom:        dataInfo.Room,
			MemberPhone:      dataInfo.Phone,
			DeviceSn:         dataInfo.DeviceSn,
			NotificationType: helper.TypeNumNotificationTypeContinues,
			Status:           helper.TypeNumNotificationStatusWait,
			Info:             "房间续住",
			ServiceInfo:      []string{dataInfo.InTime, dataInfo.LeaveTime},
		}
		//if notificationsInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(param); notificationsInfo.Id <= 0 {
		//	return
		//} else {
		//	ok := dao.NewRoomDaoDao().UpdateRoomOrder(tradeNo, thirdTradeNo, helper.TypeNumRoomOrderStatusDoneWait, amount).Err != nil
		//}
		if notificationsInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(param); notificationsInfo.Id <= 0 {
			return
		} else {
			updateParam := &room.OrderDb{
				Amount:         amount,
				TradeNo:        tradeNo,
				ThirdTradeNo:   thirdTradeNo,
				NotificationId: notificationsInfo.Id,
				Status:         helper.TypeNumRoomOrderStatusDoneWait,
			}
			if data := dao.NewRoomDaoDao().UpdateRoomOrder(updateParam); data.Err != nil {
				zap.L().Error("UpdateRoomOrder:" + data.Err.Error())
				return
			}
		}

		// 处理成功返回值设置
		ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
	}
}

// HandlePayResult 押金支付结果通知 - V2
func HandlePayResult(ctx *gin.Context) {
	// 获取请求Body
	resultData := wxpay.NewPayData()
	err := resultData.FromXml(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,支付结果通知", resultData)

	wc := logic.NewSettingLogic().GetPaySettingByAppid(resultData.Get("appid"))

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("transaction_id") || resultData.Get("transaction_id") == "" {
		zap.L().Error("transaction_id 微信订单号不存在")
		return
	}

	// 验证微信订单
	apiData := wxpay.NewPayData()
	apiData.Set("transaction_id", resultData.Get("transaction_id"))

	respData, err := wxpay.ApiOrderQuery(payClient, apiData, wc)
	if err != nil {
		zap.L().Error("error order query - 微信订单查询失败")
		return
	}

	// 验证成功
	if respData.Get("return_code") == wxpay.RCSuccess &&
		respData.Get("result_code") == wxpay.RCSuccess {
		// 业务逻辑处理 - 订单操作
		ok := logic.NewNotifyLogic().DepositPayResultNotify(respData)

		//添加订单关联操作
		ok = dao.NewOrderDao().InsertOrderCorrelation(resultData.Get("out_trade_no")).Unwrap().(bool)
		//修改优惠券状态
		//dingo.Task(logic.NewNotifyLogic().CouponPayScoreNotify, func() {}, apiData)
		//logic.NewNotifyLogic().CouponDepositNotify(apiData)
		// 处理通知
		if ok {
			//退款成功需要返回给微信

			// 处理成功返回值设置
			ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
		}
	}
}

func HandlePayResultV3(ctx *gin.Context) {
	// todo 获取请求body
	reqData := wechatpay.NewPayData()
	err := reqData.FromJson(ctx.Request.Body)
	if err != nil {
		zap.L().Error(wechatpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,支付结果通知", reqData)

	// todo 获取支付配置信息
	var wc *paysetting.PaySetting
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	} else {
		wc = logic.NewSettingLogic().GetPaySetting()
	}

	// todo 解密退款数据
	dt, err := reqData.DecryptBody(wc)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	resultData := wechatpay.NewPayData()
	err = resultData.FromJsonStr(dt)
	log.Println("打印测试数据,解密后的支付结果信息", resultData)

	ok := logic.NewNotifyLogic().DepositPayResultNotifyV3(resultData, 0)
	if ok {
		ctx.XML(200, gin.H{"return_code": "SUCCESS", "return_msg": "OK"})
	}
}

// 退款结果通知
//[
//appid:wx829e281c013a66e2
//mch_id:1600369044
//nonce_str:ba7a38feae009737f77bb4cac1e9d27e
//req_info:OJ7y6BHtJQRaPS/vL7Ya5pwCSTiuyu4Di/Y9A3iPtkIittSGFfOC/ZzZjGVlZ/iuYFIa7qkUNdqPU01/
//	SLXdaXUTyGK9SDg8KE7Gdxwkz1svdd6xogh+4/S+PwYtjjcVU4iIbl+EEZZZKvDYxiSWrgzc0paotwHirT7q1Gq+/
//	Fg1gGTnxxl7DyXTgw7Y7oZ5GKs6xNTGLQLme+jkohj/
//	BjD9dPi443JvyQ0aixDzLHUKzO9ybe1f8cLLzUogIWGBuJ8INLPkdz+
//	BTtlrsmpTabwn52mCbTHO9Kc9nEaeU587UrLeU1CrkPUhbbUYfj6vy39iAHDUpzg9PhC8ONPjcxS+
//	TmBVN+gVtesDjTQl1mDDr+dYuGZ7Aho2C4IE661kISYt0tay9aUJ6VvZGPuNb956CQ46RY4WUwMQVVzoKJ21
//IU14oBgwwG3CRC1aM5Dlf399nUKgGPDUvlGMeUAQjnaMdhXZa8IaVBmLHMcT/
//	B0Ug7dItFk50mz0A0oc2JvSr5MNMju3fNgFHWjT3t/hJjMbjhg+yrGqX/+ZlX6pG6d9UkzbRvA1gq
//zXR9pzmrbxGvZqoyoBNh8VdC1Q+FHEJrH07nwyWIm+DRA2RN4ulhxQzYZIQKw6EYui19VL0hz6gIaerzis1o40+w0Lzr4LD/
//	XuLnuB6Ui48MoWk2UfoTesGW4GO7DzL0xzkDGSPMcSaf3Iw7N/eqMp4rILnkCvAb5ljTcjwu7dCLkc0hot19mezDz6T
//kTgCRQ0jipt3rBEAqv6xq8DfZ8cTRo9whiwRfiO6ZyezJdWUrOdxmjUGXpYn5eNfe62VXWROhUXBkypAvYzKlYumHfWy7G
///qN82LBlyfFPnjTk5zXV4HDHWLrzOIpBh8mOI1AXdAlv5RH71/r2zHcPglmc+fdoU+iyo0xcyjKGIbIKuqw9M7qV7njwqc
//m8rFPbcbEO28K5NKVlkkGSpa7ycEj+otn35EZ8OyO72isuuja78Xzi6e2Mcdg3hrl/Pu9FXqy13O90TquIVeRaF0gXD4kK
//IkF7XBQYvs58B1oiiUQLV3yXfAJNghzdnTA9lYaf/9i6yGyEvniuz
//return_code:SUCCESS
//]

func HandleRefundAutomateResult(ctx *gin.Context) {
	// 获取请求Body
	reqData := wxpay.NewPayData()

	if err := reqData.FromJson(ctx.Request.Body); err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,退款结果通知", reqData)

	var wc = logic.NewSettingLogic().GetPaySetting()
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	}
	log.Println("需要解析的数据", reqData.GetMap("resource"))
	resourceDate := reqData.GetMap("resource")

	// 解密后的数据
	resultData, err := logic.NewNotifyLogic().RefundDataDeCryptoV3(resourceDate, wc.ApiKeyV3)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	log.Println("打印测试数据,解密后的退款结果信息", resultData)

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("refund_id") || resultData.Get("refund_id") == "" {
		zap.L().Error("refund_id 微信退款单号不存在")
		return
	}

	// 验证退款并更新状态
	if ok := logic.NewNotifyLogic().RefundResultAutomateNotifyV3(resultData, reqData.Get("appid"), reqData.Get("mch_id")); ok {
		ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
	}
}

func HandleRefundRoomResult(ctx *gin.Context) {
	// 获取请求Body
	reqData := wxpay.NewPayData()

	if err := reqData.FromJson(ctx.Request.Body); err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,退款结果通知", reqData)

	var wc = logic.NewSettingLogic().GetPaySetting()
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	}
	log.Println("需要解析的数据", reqData.GetMap("resource"))
	resourceDate := reqData.GetMap("resource")

	// 解密后的数据
	resultData, err := logic.NewNotifyLogic().RefundDataDeCryptoV3(resourceDate, wc.ApiKeyV3)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	log.Println("打印测试数据,解密后的退款结果信息", resultData)

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("refund_id") || resultData.Get("refund_id") == "" {
		zap.L().Error("refund_id 微信退款单号不存在")
		return
	}

	// 验证退款单号是否已存在
	if ok := logic.NewNotifyLogic().RefundResultGoodsNotifyV3(resultData, reqData.Get("appid"), reqData.Get("mch_id")); ok {
		ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
	}
}

func HandleRefundGoodsResult(ctx *gin.Context) {
	// 获取请求Body
	reqData := wxpay.NewPayData()

	if err := reqData.FromJson(ctx.Request.Body); err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	defer ctx.Request.Body.Close()
	log.Println("打印测试数据,退款结果通知", reqData)

	var wc = logic.NewSettingLogic().GetPaySetting()
	if reqData.Get("appid") != "" {
		wc = logic.NewSettingLogic().GetPaySettingByAppid(reqData.Get("appid"))
	}
	log.Println("需要解析的数据", reqData.GetMap("resource"))
	resourceDate := reqData.GetMap("resource")

	// 解密后的数据
	resultData, err := logic.NewNotifyLogic().RefundDataDeCryptoV3(resourceDate, wc.ApiKeyV3)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	log.Println("打印测试数据,解密后的退款结果信息", resultData)

	// 验证 BODY中是否存在 订单号 transaction_id
	if !resultData.IsSet("refund_id") || resultData.Get("refund_id") == "" {
		zap.L().Error("refund_id 微信退款单号不存在")
		return
	}

	// 验证退款单号是否已存在
	if ok := logic.NewNotifyLogic().RefundResultGoodsNotifyV3(resultData, reqData.Get("appid"), reqData.Get("mch_id")); ok {
		ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
	}
}

func HandleRefundResultV3(ctx *gin.Context) {
	wc := logic.NewSettingLogic().GetPaySetting()
	// 获取请求body参数
	req := ctx.Request
	postData := wechatpay.NewPayData()
	err := postData.FromJson(req.Body)
	if err != nil {
		zap.L().Error("微信退款通知确认，json转map失败，notifyhandler:HandleRefundResultV3")
		return
	}
	defer req.Body.Close()
	log.Println("打印测试数据 HandleRefundResultV3-postData", postData)

	// 获取请求头信息
	headers := map[string]string{
		"serial_no": req.Header.Get("Wechatpay-Serial"),
		"signature": req.Header.Get("Wechatpay-Signature"),
		"nonce":     req.Header.Get("Wechatpay-Nonce"),
		"timestamp": req.Header.Get("Wechatpay-Timestamp"),
	}
	log.Println("打印测试数据 HandleRefundResultV3-headers", headers)

	// 解密请求报文
	body, err := postData.DecryptBody(wc)
	if err != nil {
		zap.L().Error("微信退款通知确认，报文解析错误，notifyhandler:HandleRefundResultV3")
		return
	}
	log.Println("打印测试数据-解密的报文 body", body)

	// 验证签名
	if ok, err := logic.NewWxOrderLogic().CheckSign(headers, body); ok { // 验签通过
		apiData := wechatpay.NewPayData()
		_ = apiData.FromJsonStr(body)
		log.Println("打印测试退款请求信息", apiData)
	} else {
		if err != nil {
			zap.L().Error("微信支付支订单确认，签名验证失败，notifyhandler:HandlePayScoreResult")
			ctx.JSON(500, gin.H{"code": "FAIL", "message": "FAIL"})
			return
		}
	}
}

// 支付分订单确认结果通知
func HandlePayScoreResult(ctx *gin.Context) {
	wc := logic.NewSettingLogic().GetPaySetting()
	// 获取请求body参数
	req := ctx.Request
	postData := wechatpay.NewPayData()
	err := postData.FromJson(req.Body)
	if err != nil {
		zap.L().Error("微信支付支订单确认，json转map失败，notifyhandler:HandlePayScoreResult")
		return
	}
	defer req.Body.Close()
	//log.Println("打印测试数据 HandlePayScoreResult-postData", postData)

	// 获取请求头信息
	headers := map[string]string{
		"serial_no": req.Header.Get("Wechatpay-Serial"),
		"signature": req.Header.Get("Wechatpay-Signature"),
		"nonce":     req.Header.Get("Wechatpay-Nonce"),
		"timestamp": req.Header.Get("Wechatpay-Timestamp"),
	}
	//log.Println("打印测试数据 HandlePayScoreResult-headers", headers)

	// 解密请求报文
	body, err := postData.DecryptBody(wc)
	if err != nil {
		zap.L().Error("微信支付支订单确认，报文解析错误，notifyhandler:HandlePayScoreResult")
		return
	}
	//log.Println("打印测试数据-解密的报文 body", body)

	// 验证签名
	if ok, err := logic.NewWxOrderLogic().CheckSign(headers, body); ok { // 验签通过
		apiData := wechatpay.NewPayData()
		_ = apiData.FromJsonStr(body)

		var b bool
		if apiData.Get("collection") != "" { // 有收款信息,支付成功通知 (非0元完结后返回)
			endTime := time.Now().Unix()
			b = logic.NewNotifyLogic().SyncOrderInfoComplete(apiData, endTime) // 同步订单信息
			logic.NewNotifyLogic().CalOrderDividends(apiData, endTime)         // 分红
			logic.NewNotifyLogic().CouponPayScoreNotify(apiData)               // 同步优惠券信息
		} else if apiData.Get("state") == "DONE" {
			m := orders.New()
			m.TradeNo = apiData.Get("out_order_no")
			m.State = 5
			m.SettlementState = 3
			m.TradeState = apiData.Get("state")
			m.TradeStateDesc = "服务订单完成"
			m.EndAt = dingo.Time(time.Now().Unix())
			//修改优惠券
			logic.NewNotifyLogic().CouponPayScoreNotify(apiData)
			//同步订单信息

			b = dao.NewOrderDao().UpdateOrderByTradeNo(m).Unwrap().(bool)
		} else {
			//respData, err := wechatpay.ApiQueryPayScoreOrder(apiData.Get("out_order_no"), wc) // 查询微信订单
			//if err != nil {
			//	zap.L().Error("微信支付支订单确认，查询微信订单失败，notifyhandler:HandlePayScoreResult")
			//	return
			//}

			orderInfo := dao.NewOrderDao().GetOrderInfoByTradeNo(apiData.Get("out_order_no")).Unwrap().(*orders.OrderModel)
			if orderInfo.Id > 0 { // 验证订单是否存在
				b = logic.NewNotifyLogic().SyncOrderInfoServing(apiData) // 同步订单
			} else { // 创建订单
				b = logic.NewNotifyLogic().CreatePayScoreOrder(apiData)
				//添加订单关联操作
				ok = dao.NewOrderDao().InsertOrderCorrelation(apiData.Get("out_order_no")).Unwrap().(bool)
			}
		}
		if b {
			//logic.NewNotifyLogic().CouponPayScoreNotify(apiData)
			log.Println("打印测试 -- 通知返回")
			ctx.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})

			return
		} else {
			zap.L().Error("微信支付支订单确认，创建商户订单失败，notifyhandler:HandlePayScoreResult")
			ctx.JSON(500, gin.H{"code": "FAIL", "message": "FAIL"})
			return
		}
	} else {
		if err != nil {
			zap.L().Error("微信支付支订单确认，签名验证失败，notifyhandler:HandlePayScoreResult")
			ctx.JSON(500, gin.H{"code": "FAIL", "message": "FAIL"})
			return
		}
	}
}

// 消息通知 校验
func HandleMessageResultVerify(ctx *gin.Context) {
	//signature := ctx.DefaultQuery("signature", "")
	//timestamp := ctx.DefaultQuery("timestamp", "")
	//nonce := ctx.DefaultQuery("nonce", "")
	echostr := ctx.DefaultQuery("echostr", "")

	ctx.Writer.Header().Add("Content-Type", "text/plain")
	ctx.Writer.Write([]byte(echostr))
}

// 消息通知 回调结果
func HandleMessageResult(ctx *gin.Context) {
	//signature := ctx.DefaultQuery("signature", "")
	//timestamp := ctx.DefaultQuery("timestamp", "")
	//nonce := ctx.DefaultQuery("nonce", "")
	echostr := ctx.DefaultQuery("echostr", "")

	//context.Response.ContentType = "text/plain";
	//context.Response.Write(data);

	ctx.Writer.Header().Add("Content-Type", "text/plain")
	ctx.Writer.Write([]byte(echostr))
	//ctx.String(200, echostr)
}

//投诉通知回调
func HandleComplaints(c *gin.Context) {
	// 获取请求Body
	reqData := map[string]interface{}{}
	buf := wechatpay.BufPool.Get().(*bytes.Buffer)
	buf.Reset()
	defer wechatpay.BufPool.Put(buf)

	_, err := buf.ReadFrom(c.Request.Body)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	err = json.Unmarshal(buf.Bytes(), &reqData)
	if err != nil {
		zap.L().Error(wxpay.RCFail)
		return
	}
	log.Println("需要解析的数据", reqData["resource"])
	resource := reqData["resource"].(map[string]interface{})

	wc := logic.NewSettingLogic().GetPaySetting()
	//解密
	resultData, err := logic.NewNotifyLogic().DecryptionNotifyLogic(resource, wc.ApiKeyV3)
	if err != nil {
		zap.L().Error(err.Error())
		return
	}
	log.Println("打印测试数据,解密后的退款结果信息", resultData)

	//业务操作

}
